package net.towee.server.authentication.impl;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.towee.server.authentication.SessionAuthManager;

import org.eclipse.jetty.server.HttpConnection;
import org.eclipse.jetty.server.Request;

import com.google.inject.Inject;

/**
 * Filter requests to socket.io. All requests MUST be authenticated
 * 
 * @author c58
 */
public class AuthenticationFilter implements Filter {
	private final SessionAuthManager sessionManager;

	@Inject
	public AuthenticationFilter(SessionAuthManager sessionManager) {
		this.sessionManager = sessionManager;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// Get session
		String cookieId = null;
		for(Cookie c : ((HttpServletRequest) request).getCookies())
			if(c.getName().equals("__towee_rem_id"))
				cookieId = c.getValue();
		
		HttpSession session = ((HttpServletRequest) request).getSession();

		// Check authentication
		if (sessionManager.getLoggedInUser(session, cookieId) == null) {
			// Safely close connection
			Request base_request = (request instanceof Request) ? (Request) request : HttpConnection
					.getCurrentConnection().getRequest();
			base_request.getConnection().getEndPoint().close();
		} else
			chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

	@Override
	public void destroy() {
	}
}
